<template>
  <div @contextmenu="contextmenu($event)">
    <div key="key2"  v-if="show">
      <slot name="filter" v-bind="{filter}"></slot>
    </div>
    <div key="key1"  v-if="!show">
      <slot name="filter" v-bind="{filter}"></slot>
    </div>
    <div class="dialogFilter" ref="content" :style="{top: screenY+'px',left:screenX+'px',zIndex:zIndex,visibility:zIndex!==-1?'unset':'hidden'}">
      <el-tree
        :data="treeData"
        show-checkbox
        default-expand-all
        node-key="_zhixin_id"
        ref="tree"
        :props="defaultProps"
        @check="check"
      ></el-tree>
      <div>
        <el-button @click="finished">完成</el-button>
      </div>
    </div>
  </div>
</template>

<script>/**
 * 不该变其他组件的任何外观，添加右键支持
 * 功能是传入表头实现过滤传出，要支持多级表头，也就是要支持tree，所以使用el-tree作为核心
 */
import { deepClone } from '../../utils'
import { TreeUtils } from '../../utils/TreeUtils'

export default {
  name: 'FilterTableHead',
  props: {
    headList: {
      type: Array,
      default:()=>{
        return []
      }
    },
  },
  watch:{
    headList:{
      deep:true,
      immediate:true,
      handler(val){
        const clone = deepClone(val) || []
        let ids = []
        TreeUtils.treeForEach(clone, (item, parent, index) => {
          const id = parent?._zhixin_id + '_' + index
          ids.push(id)
          this.$set(item, '_zhixin_id', id)
        })
        this.treeData = clone
        this.$nextTick(()=>{
          this.$refs.tree.setCheckedKeys(ids)
          this.$nextTick(()=>{
            this.check()
          })
        })
      }
    }
  },
  data(){
    return{
      show:true,
      treeData:[],
      defaultProps:{
        children: 'children',
        label: 'label'
      },
      filter:[],
      screenX:0,
      screenY:0,
      zIndex: -1
    }
  },
  methods:{
    contextmenu(event){
      event.preventDefault();//阻止浏览器 默认事件
      this.screenY=event.clientY
      this.screenX=event.clientX
      this.zIndex='auto'
      const height = this.$refs.content.scrollHeight
      const width = this.$refs.content.scrollWidth
      if (this.screenY + height > window.innerHeight) {
        this.screenY = window.innerHeight - height - 10
      }
      if (this.screenX + width > window.innerWidth) {
        this.screenX = window.innerWidth - width - 10
      }
    },
    finished(){
      this.zIndex = -1
    },
    check(){
      this.filter=this.$refs.tree.getCheckedNodes()
      this.show=!this.show
    }
  }
}
</script>

<style scoped lang="scss">
.dialogFilter{
  position: fixed;
  z-index: -1;
  visibility: hidden;
  .el-tree{
    padding-bottom: 20px;
    padding-right: 20px;
  }
}
</style>
